import { login, logout, getUserInfo } from '@/api/user'

const state = {
    token: localStorage.getItem('token') || '',
    userInfo: null
}

const getters = {
    token: state => state.token,
    userInfo: state => state.userInfo
}

const actions = {
    async login(context,value){
        const res = await login(value);
        const token = res.data;
        if(token){
            context.commit('SET_TOKEN',token);
        }else{
            throw new Error('登录失败：未获取到token');
        }
    },
    logout(context) {
        return new Promise((resolve) => {
            localStorage.removeItem('token');
            context.commit('SET_TOKEN', '');
            context.commit('SET_USER_INFO', null);
            resolve();
        });
    },
    async getUserInfo(context,value) {
        const userInfo = await getUserInfo(value);
        context.commit('SET_USER_INFO', userInfo.data);
        return userInfo;
    }
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token;
        if(token){
            localStorage.setItem('token', token);
        }
    },
    SET_USER_INFO: (state, userInfo) => {
        state.userInfo = userInfo;
    }
}

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}